import axios from 'axios'
import store from '../store';
import {
  Message
} from 'element-ui'
import querystring from 'querystring' //序列化请求参数
import {
  config
} from '../../static/config'
// console.log(getLocalStorage("token"))
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
let baseURL = config.url.baseUrl

axios.defaults.baseURL = baseURL
axios.defaults.withCredentials = true
window.store = store;

export default function request(url, type = 'GET', data = {}, config = {
  showProgress: true,
  uploadModel: false,
  isToken: true,
  configurl: undefined
}) {
  return new Promise((resolve, reject) => {
    if (config.showProgress == undefined) config.showProgress = true
    if (config.uploadModel == undefined) config.uploadModel = false
    if (config.isToken == undefined) config.isToken = true

    if (config.configurl != undefined) {
      axios.defaults.baseURL = config.configurl
    } else {
      axios.defaults.baseURL = baseURL
    }
    if (config.showProgress) store.dispatch('showProgress', {
      status: 'start'
    })
    let option = {
      url,
      method: type
    }
    if (type.toLowerCase() === 'get') {
      option.params = data
    } else {
      option.data = data
    }
    if (config.uploadModel) {
      console.log(window.location.href)
      if (localStorage.getItem('user') == undefined) return
      option.headers = {
        'Content-Type': 'multipart/form-data;charset=UTF-8'
      }
    }
    if (config.isToken) {
      console.log(window.location.href)
      if (localStorage.getItem('user') == undefined) return
      option.headers = {
        'Authorization': `Bearer ${JSON.parse(localStorage.getItem('user')).accessToken}`
      }
      // localStorage.getItem('user')
    }

    axios(option).then(res => { //axios的res被封装了一次 所以真实数据在res.data中
      if (res.data.success) {
        // setTimeout(() => {
          store.dispatch('showProgress', {
            status: 'over'
          })
        // }, Math.floor((Math.random()) * 30))
        resolve(res.data)
      } else {
        if (res.data.code == 401) {
            // console.log()
            window.location.href = `http://${window.location.host}/login?redirect=${window.location.pathname + window.location.search}`
        }
        reject(res.data)
      }
    }).catch(err => {
      reject({
        msg: '网络异常:' + err
      })
    })
  })
}


// request('/auth/login', 'POST', {username: 'hunger', password: '123456'})
//   .then(data=>{
//     console.log(data)
//   })
